package com.example.JcGQS.response;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @ClassName ResultAdvice
 * @Description
 *
 * @author 末日
 * @date 2023/11/21
 */
@RestControllerAdvice("com.example.JcGQS.controller")
@Slf4j
public class ResultAdvice implements ResponseBodyAdvice<Object> {

    /**
     * @Title supports
     * @Description 是否开启统一封装
     *
     * @param returnType
     * @param converterType
     * @return boolean
     * @see ResponseBodyAdvice#supports(MethodParameter,
     *      Class)
     */
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 过滤ResultUtil
        return !returnType.getParameterType().equals(ResultUtil.class);
    }

    /**
     * @Title beforeBodyWrite
     * @Description 在返回数据之前统一封装
     *
     * @param body
     *            返回数据
     * @param returnType
     * @param selectedContentType
     * @param selectedConverterType
     * @param request
     * @param response
     * @return Object
     */
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType,
        Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request,
        ServerHttpResponse response) {
        //解决返回的值类型为String类型时，就会发生异常
        if (body instanceof String) {
            ObjectMapper om = new ObjectMapper();
            try {
                return om.writeValueAsString(ResultUtil.success(body));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
        }
        if (body instanceof ResultUtil) {
            return body;
        }
    	return  ResultUtil.success(body);
    }

}
